
import { createStore } from 'vuex'
import { deepClone } from '../utils/utils'

import RCIMIWEngine from "@/uni_modules/RongCloud-IMWrapper-V2/js_sdk/RCIMEngine"

const store = createStore({
	state: {
		myinfo: null,
		engine: null,
		appkey: 'mgb7ka1nm2a7g',
		conversationList: [], // 会话列表
		systemlist: [],//消息通知列表
		bg_photo: {},//背景图片
		friendinfo: {//存储朋友的信息

		},
		getMessages: [],//对话消息
		targetId: null,//会话Id
		options: {},
		citys: null, //选中的市区列表
		niolist: false
		/* {
	"SC241230093316ENVMLWH8": {
		"avatar": "https://fan-qr-code.oss-cn-shenzhen.aliyuncs.com/ea099e61-9bc3-4b3d-afb1-081614c98527.jpg",
		"remark_name": "小帅",
		"system_code": "SC241230093316ENVMLWH8"
	},
	"SC250107104505HYV5G8H5": {
		"avatar": "https://fan-qr-code.oss-cn-shenzhen.aliyuncs.com/865dba28-312d-474f-a40a-a3b8ea077002.jpg",
		"remark_name": "小美",
		"system_code": "SC250107104505HYV5G8H5"
	}
} */
		//getMessages:[],//对话消息
	},
	mutations: {
		setmyinfo(state, data) {
			state.myinfo = data
		}, setbg_photo(state, data) {
			state.bg_photo = data
		},
		deletegetMessages(state, data) {
			let index = state.getMessages.findIndex(item => item.messageUId === data.messageUId);

			if (index !== -1) {
				// 使用splice删除元素
				state.getMessages.splice(index, 1);
			}

		},
		deleteallgetMessages(state, data) {
			state.getMessages = []

		},
		setfriendinfo(state, data) {
			//console.log('setfriendinfosetfriendinfosetfriendinfo', data)
			state.friendinfo = data
		},
		setcitys(state, data) {
			//console.log('vuex',data);

			state.citys = data
		},
		setsystemlist(state, data) {
			if (!state.systemlist.length) {
				state.systemlist = data.list
				return
			}
			let array = deepClone(state.systemlist)
			data.list.forEach(sourceItem => {
				const index = array.findIndex(targetItem => targetItem.targetId === sourceItem.targetId);
				if (index !== -1) {
					array.splice(index, 1);
					array.unshift(sourceItem)
				} else {
					array.push(sourceItem)
				}
			});
		},
		deleteconversationList(state, data) {
			console.log('回话列表删除的index是-----', data.index)
			state.conversationList.splice(data.index, 1)
			console
		},
		setconversationList(state, data) {

			if (!state.conversationList.length) {
				state.conversationList = data.list
				return
			}
			if (data?.type == 2) {//重新加载
				let array = deepClone(data.list)
				state.conversationList.forEach(sourceItem => {
					const index = array.findIndex(targetItem => targetItem.targetId === sourceItem.targetId);
					console.log('data.targetIddata.targetIddata.targetIddata.targetIddata.targetIddata.targetId', data.targetId)
					console.log('sourceItem.targetIdsourceItem.targetIdsourceItem.targetIdsourceItem.targetId', sourceItem.targetId)
					console.log('indexindexindexindexindexindexindexindex', index)
					if (index !== -1 && data.targetId == sourceItem.targetId) {
						array.splice(index, 1);
						array.unshift(sourceItem)
					} else if (index !== -1 && data.targetId != sourceItem.targetId) {
						// array[index]=sourceItem
					} else if (data.targetId != sourceItem.targetId && index == -1) {
						array.push(sourceItem)
					}
				});
				state.conversationList = array
			} else if (data?.type == 3) {//加载更多
				let array = deepClone(state.conversationList)
				data.list.forEach(sourceItem => {
					const index = array.findIndex(targetItem => targetItem.targetId === sourceItem.targetId);
					console.log('data.targetIddata.targetIddata.targetIddata.targetIddata.targetIddata.targetId', data.targetId)
					console.log('sourceItem.targetIdsourceItem.targetIdsourceItem.targetIdsourceItem.targetId', sourceItem.targetId)
					console.log('indexindexindexindexindexindexindexindex', index)
					if (index !== -1 && data.targetId == sourceItem.targetId) {
						array.splice(index, 1);
						array.unshift(sourceItem)
					} else if (data.targetId != sourceItem.targetId && index == -1) {
						array.push(sourceItem)
					}
				});

				state.conversationList = array
			}


			console.log('最后的会话列表是------------', state.conversationList)


			// 	if(!state.conversationList.length){
			// 		state.conversationList=data.list
			// 		return
			// 	}

			// 	let array =deepClone(state.conversationList)
			// 	data.list.forEach(sourceItem => {
			// 		const index = array.findIndex(targetItem => targetItem.targetId === sourceItem.targetId);
			// 		console.log('data.targetIddata.targetIddata.targetIddata.targetIddata.targetIddata.targetId',data.targetId)
			// 		console.log('sourceItem.targetIdsourceItem.targetIdsourceItem.targetIdsourceItem.targetId',sourceItem.targetId)
			// 		console.log('indexindexindexindexindexindexindexindex',index)
			// 		if(index !== -1&&data.targetId==sourceItem.targetId){
			// 			array.splice(index, 1);
			// 			array.unshift(sourceItem)
			// 		}else if(index !== -1&&data.targetId!=sourceItem.targetId) {
			// 			array[index]=sourceItem
			// 		}else if(data.targetId!=sourceItem.targetId&&index == -1){
			// 			array.push(sourceItem)
			// 		}
			// 	});
			// 	state.conversationList =array

		},
		cleargetMessages(state, data) {
			state.getMessages = []
		},
		clearall(state, data) {
			state.myinfo = null
			state.engine = null
			state.conversationList = []
			state.systemlist = []
			state.bg_photo = {}
			state.friendinfo = {}
			state.getMessages = []
			state.targetId = null
			state.options = {}
			state.citys = null
			state.niolist = false
			console.log('清除之后的state----------------', state)


		},
		setnolist(state, data) {
			state.niolist = data
		},
		setMessages(state, data) {


			if (!state.getMessages.length) {
				state.getMessages = data.list
				return
			}

			let array = deepClone(state.getMessages)
			console.log('arrayarrayarrayarrayarrayarrayarray', array)
			console.log('data.listdata.listdata.listdata.listdata.list', data.list)
			data.list.forEach(sourceItem => {
				const index = array.findIndex(targetItem => targetItem.messageUId === sourceItem.messageUId);
				console.log('sourceItem.targetIdsourceItem.targetIdsourceItem.targetIdsourceItem.targetId', sourceItem.messageUId)
				console.log('indexindexindexindexindexindexindexindex', index)
				if (index !== -1) {
					array[index] = sourceItem
				} else {
					if (data.status) {
						array.push(sourceItem)
					} else {
						array.unshift(sourceItem)
					}

				}
			});
			state.getMessages = array
			console.log('state.getMessagesstate.getMessagesstate.getMessagesstate.getMessages', state.getMessages)



			// data.map(item => {
			// 	//state.getMessages={}  

			// 	//Object.keys(store.state.getMessages).reverse()
			// 	state.getMessages['chat' + item.sentTime + item.messageUId] = item
			// 	//state.getMessages.push(item)   
			// })
			//state.getMessages=store.state.getMessages.reverse()
			//console.log('state.getMessagesstate.getMessagesstate.getMessages--------',state.getMessages)
		},
		settargetId(state, data) {
			state.targetId = data
		},
		setengine(state, data) {
			state.engine = data
		},

	},
	actions: {
		async init({ state, commit, dispatch }) {
			//console.log('state------------------------------------------------------',state)
			let options = {}
			let engine = await RCIMIWEngine.create('mgb7ka1nm2a7g', options);
			commit('setengine', engine)
			//console.log('engine------------',engine)
			let callback = {
				onDatabaseOpened: (res) => {
					//console.log('onDatabaseOpened------', res)
					//...
				},
				onConnected: (res) => {
					//console.log('onConnected------', res)
					//...
				}
			};

			//console.log('rongyun_tokenrongyun_token-----------', { rongyun_token: uni.getStorageSync('rongyun_token') })
			//console.log('app_tokenapp_token-----------', { app_token: uni.getStorageSync('app_token') })
			let code = await state.engine.connect(uni.getStorageSync('rongyun_token'), 60, callback);

			//收到连接状态的回调
			state.engine.setOnDatabaseOpenedListener((res) => {
				console.log('setOnDatabaseOpenedListener收到连接状态的回调----------------', res)
				//...
			});

			//收到连接状态的回调
			state.engine.setOnConnectedListener((res) => {
				console.log('setOnConnectedListener收到连接状态的回调-----------', res)
				//...
			});

			//断开连接
			//let code = await engine.disconnect(receivePush);

			//监听连接状态
			state.engine.setOnConnectionStatusChangedListener((res) => {
				if (res.status == 1) {
					let datas = {
						num: 0,
						targetId: null,
						type: 2
					}
					console.log('监听连接状态datasdatasdatasdatasdatas--------------------', datas)
					dispatch('getConversations', datas)
				}

				console.log('监听连接状态--------------------', res)
				//...
			});

			//设置消息监听
			state.engine.setOnMessageReceivedListener((res) => {
				console.log('消息监听setOnMessageReceivedListener------', res)
				// let datas = {
				// 	num:0,
				// 	targetId:res.message.targetId
				// }
				let datas = {
					num: 0,
					targetId: null,
					type: 2
				}
				dispatch('getConversations', datas)


				if (state.targetId) {
					let datas2 = {
						targetId: state.targetId,
						times: res.message.sentTime,
						type: 1
					}
					dispatch('getMessages', datas2)
				}
				//...
			});

			//发送消息回调
			state.engine.setOnMessageAttachedListener((res) => {
				console.log('发送消息回调setOnMessageAttachedListener', res)
				if (state.targetId) {
					//dispatch('getMessages')
					// let datas = {
					// 	num:0,
					// 	targetId:null
					// }
					// dispatch('getConversations', datas)
				}

				//...
			});

			/*  */

			//退出登录
			// 断开链接，是否继续接收推送
			// let receivePush = true
			// let code = await yourEngine.disconnect(receivePush)


			//销毁引擎
			//let code = await yourEngine.destroy()



		},
		async disconnect({ state, commit, dispatch }) {//断开连接
			let code = await state.engine.disconnect(false);
			console.log('退出状态是-------', code)
			commit('clearall', {})
			uni.setStorageSync('myinfo', '')
		},

		async getsystem({ state, commit, dispatch }) {//系统消息列表
			//console.log('111111111111111')
			//会话列表
			let callbacks = {
				onSuccess: (res) => {
					console.log('系统消息列表onSuccess-------------------------------------------------------', res.t)
					if (res.t.length > 0) {
						let data = {
							list: res.t
						}
						console.log('datadatadatadatadatadatadatadatadatadata', data)
						commit('setsystemlist', data)
					}

					//...
				},
				onError: (res) => {
					//console.log('会话列表onError-----------------------------------------------------', res)
					//...
				}
			};
			
			let conversationTypes = [4]


			let codes = null

			/* state.conversationList[Object.keys(state.conversationList)[Object.keys(state.conversationList).length - 1]].operationTime */
			codes = await state.engine.getConversations(conversationTypes, null, datas.num, 50, callbacks);

		},
		async getConversations({ state, commit, dispatch }, datas) {//获取会话列表
			console.log('datas.targetIddatas.targetIddatas.targetIddatas.targetIddatas.targetIds', datas)
			//console.log('111111111111111')
			//会话列表
			let callbacks = {
				onSuccess: (res) => {
					console.log('会话列表onSuccess-------------------------------------------------------', res.t)
					if (res.t.length > 0) {
						let data = {
							list: res.t,
							...datas
						}
						commit('setconversationList', data)

						if (datas?.type == 1) {
							console.log('-----------state.conversationListstate.conversationList-------------', state.conversationList)
							let indexs2 = res.t.findIndex(items => items.targetId === datas.targetId)

							let datas2 = {
								targetId: datas.targetId,
								times: res.t[indexs2]?.operationTime || 0,//state.conversationList[0].operationTime,
								type: 1
							}

							console.log('获取对话的参数是-------------', datas2)
							dispatch("getMessages", datas2)
						}
					}

					//...
				},
				onError: (res) => {
					//console.log('会话列表onError-----------------------------------------------------', res)
					//...
				}
			};
			let conversationTypes = [1]


			let codes = null

			/* state.conversationList[Object.keys(state.conversationList)[Object.keys(state.conversationList).length - 1]].operationTime */
			codes = await state.engine.getConversations(conversationTypes, null, datas.num, 50, callbacks);
			

		},
		async getMessages({ state, commit, dispatch }, datas) {//获取对话信息
			if (state.niolist && datas?.type != 1) return
			if (datas.targetId || state.targetId) {
				if (datas.targetId) {
					commit('settargetId', datas.targetId)
				}

				let callback = {
					onSuccess: (res) => {
						console.log('获取对话信息获取对话信息获取对话信息获取对话信息获取对话信息获取对话信息', res.t)
						if (res.t.length < 15) {
							commit('setnolist', true)
						} else {
							commit('setnolist', false)
						}
						let datas2 = {
							list: res.t,
							status: datas.status || 0
						}
						//.reverse()
						commit('setMessages', datas2)

						//...
					},
					onError: (res) => {
						//...
					}
				};
				let code = await state.engine.getMessages(1, datas.targetId || state.targetId, null, datas.times + 10000, 0, 2, 15, callback);
			}

		}



	}

})


export default store